package com.premedsidekick;
//ArrayAdapter to output custom ListView
//XML: rowbuttonlayout.xml
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
//import android.widget.Toast;
public class CheckBoxArrayAdapter extends ArrayAdapter<String> {
	private final Activity context;
	private final String[] names;
	SharedPreferences preferences;
	SharedPreferences.Editor editor;
	String filename;
	
	//added
	//private ArrayList<String> checkList = new ArrayList<String>();
	TextView textView;
	CheckBox cBox;
	
	public CheckBoxArrayAdapter(Activity context, String[] names) {
		super(context, R.layout.rowbuttonlayout, names);
		this.context = context;
		this.names = names;
		filename = "mcat_file";
		preferences = context.getSharedPreferences (filename, 0);
		editor = preferences.edit();
	}
	/*
	// static to save the reference to the outer class and to avoid access to
	// any members of the containing class
	static class ViewHolder {
		//public ImageView imageView;
		public TextView textView;
		public CheckBox cBox;
	}
	*/
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// ViewHolder will buffer the assess to the individual fields of the row
		// layout

		//ViewHolder holder;
		// Recycle existing view if passed as parameter
		// This will save memory and time on Android
		// This only works if the base layout for all classes are the same
		
		View rowView = convertView;
		if (rowView == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			rowView = inflater.inflate(R.layout.rowbuttonlayout, null, true);
		}
		
		//holder = new ViewHolder();
		textView = (TextView) rowView.findViewById(R.id.line1);
		textView.setText (names[position]);
		cBox = (CheckBox) rowView.findViewById(R.id.rightbox);
		//added
		cBox.setTag(position);
		if (preferences.getBoolean(names[position].substring(0, 7), false) == true)
			cBox.setChecked(true);
		cBox.setOnClickListener (new OnClickListener() {
			@Override
			public void onClick (View v) {
				CheckBox cBox = (CheckBox) v.findViewById(R.id.rightbox);
				String num = cBox.getTag().toString();
				int what = Integer.parseInt(num);
				if (!cBox.isChecked()) {
					editor.putBoolean((String)names[what].substring(0, 7), false);
				}
				else if (cBox.isChecked()) {
					editor.putBoolean((String)names[what].substring(0, 7), true);
				}
				editor.commit();
			}
		});
		
		//System.out.println(R.id.rightbox);
		//rowView.setTag(holder);
		//} else {
		//	holder = (ViewHolder) rowView.getTag();
		//}
		//holder.textView.setText (names[position]);
		return rowView;
	}
}